package Utils;

import java.nio.ByteBuffer;
import javax.xml.bind.DatatypeConverter;
import ArithUtils.*;

/**
 * A class which holds useful conventions methods.
 * 
 * @author Itamar Carmel
 */
public class TypeConvertionUtils {
	
	/**
	 * Convert String to byte array.
	 * 
	 * @param str
	 * @return byteArray(str)
	 */
	public static byte[] stringToByteArr(String str){
		return str.getBytes();
	}
	
	/**
	 * Convert byte array to String.
	 * 
	 * @param byteArr
	 * @return String(byteArr)
	 */
	public static String byteArrToString(byte[] byteArr){
		return new String(byteArr);
	}
	
	/**
	 * Convert integer to byte array.
	 * 
	 * @param i
	 * @return byteArray(i)
	 */
	public static byte[] intToByteArr(int i){
		ByteBuffer bb = ByteBuffer.allocate(4);
		bb.putInt(i);
		return bb.array();
	}
	
	/**
	 * Convert byte array to integer.
	 * 
	 * @param byteArr
	 * @return integer(byteArr)
	 */
	public static int byteArrToInt(byte[] byteArr){
		if (byteArr.length != 4){
			System.err.println("ERROR: Illegal int representation - byte array should contain exactly 4 bytes.");
			return 0;
		}
		ByteBuffer bb = ByteBuffer.wrap(byteArr);
		return bb.getInt();
	}
	
	/**
	 * Convert String (in hex rep.) to byte array.
	 * 
	 * @param hex_str
	 * @return byteArray(hex_str)
	 */
	public static byte[] hexStringToByteArr(String str){
		if (str.length() % 2 != 0){
			System.err.println("ERROR: Illegal byte representation - hex string should have an even length.");
			return null;
		}
		return DatatypeConverter.parseHexBinary(str);
	}
	
	/**
	 * Convert byte array to String (in hex rep.).
	 * 
	 * @param byteArr
	 * @return hex_string(byteArr)
	 */
	public static String byteArrToHexString(byte[] byteArr){
		StringBuilder sb = new StringBuilder();
		for(byte b: byteArr){
			sb.append(String.format("%02x", b&0xff));
		}
		return sb.toString();
	}
	
	/**
	 * Convert BN to integer.
	 * 
	 * @param bn
	 * @return integer(bn)
	 */
	public static int bigNumberToInt(BigNumber bn){
		return Integer.parseInt(bn.toString());
	}

}
